<template>
  <page>
    <template v-slot:header>
      <h2>
        <i class="icon iconfont">&#xe69d;</i>
        <span>{{ $t("configure.configure_item_manager") }}</span>
      </h2>
    </template>
    <template v-slot:content>
      <el-dialog
        :title="title"
        :visible.sync="display"
        :before-close="handleClose"
      >
        <host-install
          @click="handleClose"
          :ids="ids"
          :osVersion="osVersion"
          :osArch="osArch"
          :osName="osName"
          v-if="type === 'hostInstall'"
        ></host-install>
        <batchInstall
          @click="handleClose"
          :osVersion="osVersion"
          :osArch="osArch"
          :ids="ids"
          :osName="osName"
          v-else-if="type === 'batchInstall'"
        ></batchInstall>
        <create-or-update
          v-else-if="type === 'create_update'"
          :row_id="edit_id"
          :d_normal="d_normal"
          @click="handleClose"
          :disableName="disableName"
        ></create-or-update>
        <delete
          v-else-if="type === 'delete'"
          :content="delete_content"
          :handleCancel="handleClose"
          :handleOk="handleDeleteOk"
        >
        </delete>
      </el-dialog>
      <p>{{ $t("configure.normal_library_configure_table_description") }}</p>
      <ky-table
        :getData="getConfigureItem"
        :search_data="search_data"
        :search_criteria="search_criteria"
        ref="table"
        :showSelect="true"
      >
        <template v-slot:table-action>
          <authorization-button
            class="kylin-item-button"
            @click="handleAdd"
            name="config:create"
          >
            {{ $t("add") }}
          </authorization-button>
          <el-dropdown trigger="click">
            <el-button
              class="kylin-item-button"
              :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >
              {{ $t("action")
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <authorization-dropdown-item @click.native="handleDelete" name="config:delete">{{
                $t("delete")
              }}</authorization-dropdown-item>
              <authorization-dropdown-item @click.native="handleHostIssue" name="Issue:issue">{{
                $t("configure.host_issue")
              }}</authorization-dropdown-item>
              <authorization-dropdown-item @click.native="handleBatchIssue" name="Issue:batchIssue">{{
                $t("configure.batch_issue")
              }}</authorization-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-slot:table>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-form label-position="left" inline>
                <el-form-item :label="$t('description')">
                  <span>{{ scope.row.description }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column :label="$t('name')" prop="name"> </el-table-column>
          <el-table-column
            prop="standardName"
            :label="$t('configure.normal_library_name')"
          >
          </el-table-column>
          <el-table-column
            prop="standardArch"
            :label="$t('system.architecture')"
          >
          </el-table-column>
          <el-table-column prop="standardVersion" :label="$t('system.version')">
          </el-table-column>
          <el-table-column
            prop="configType"
            :label="$t('configure.configure_type')"
          >
          </el-table-column>
          <el-table-column prop="attribute" :label="$t('attribute')">
          </el-table-column>
          <el-table-column
            prop="baseline"
            :label="$t('configure.configure_value')"
          >
          </el-table-column>
          <el-table-column prop="flag" :label="$t('configure.restart_sign')">
          </el-table-column>
          <el-table-column prop="filePath" :label="$t('configure.file_path')">
          </el-table-column>
          <el-table-column :label="$t('action')">
            <template slot-scope="scope">
              <authorization-button
                @click.native.prevent="handleEdit(scope.row)"
                type="text"
                size="medium"
                name="config:update"
              >
                {{ $t("edit") }}
              </authorization-button>
            </template>
          </el-table-column>
        </template>
      </ky-table>
    </template>
  </page>
</template>

<script>
import Page from "@/components/Page";
import kyTable from "@/components/KyTable";
import AuthorizationDropdownItem from "@/components/AuthorizationDropdownItem";
import {
  getConfigureItem,
  deleteConfigureItem,
  getClassInfo,
  getStandardLib,
} from "@/api/config";
import CreateOrUpdate from "../normalLibrary/form/create_or_update.vue";
import hostInstall from "./form/hostInstall.vue";
import batchInstall from "./form/batchInstall.vue";
import Delete from "@/components/Delete";
import AuthorizationButton from "@/components/AuthorizationButton";
export default {
  name: "configure_item",
  components: {
    Page,
    kyTable,
    CreateOrUpdate,
    hostInstall,
    batchInstall,
    Delete,
    AuthorizationButton,
    AuthorizationDropdownItem
  },
  activated() {
      this.$refs.table.handleSearch();
  },
  methods: {
    getConfigureItem,
    handleEdit(row) {
      this.display = true;
      this.title = this.$t("configure.edit_configure_item");
      this.edit_id = row.id;
      this.type = "create_update";
      this.disableName = true;
    },
    handleAdd() {
      this.display = true;
      this.type = "create_update";
      this.title = this.$t("configure.add_configure_item");
    },
    handleDelete() {
      this.display = true;
      this.type = "delete";
      this.title = this.$t("configure.delete_configure");
      let arr = [];
      let str = "";
      if (this.$refs.table.select_id == "2") {
        str = this.$refs.table.select_number.toString();
      } else {
        this.$refs.table.selectRow.rows.map(function (row) {
          arr.push(row.name);
        });
        str = arr.toString();
      }
      this.delete_content = this.$t(
        "configure.delete_configure_content"
      ).replace("%s", str);
    },
    handleClose(type) {
      this.disableName = false;
      this.display = false;
      this.edit_id = null;
      this.type = "";
      if (type === "success") {
        this.$refs.table.refresh();
      }
    },
    async getConfigureNews() {
      let osName = new Set();
      let osVersion = new Set();
      let osArch = new Set();
      let ids = [];
      if (this.$refs.table.select_id == "2") {
        const res = await getConfigureItem({
          ...this.$route.query,
          paged: false,
        });
        res.data.data.results.map((item) => {
          ids.push(item.id);
          osName.add(item.standardName);
          osVersion.add(item.standardVersion);
          osArch.add(item.standardArch);
        });
      } else {
        this.$refs.table.selectRow.rows.forEach((row) => {
          osName.add(row.standardName);
          osVersion.add(row.standardVersion);
          osArch.add(row.standardArch);
        });
        ids = this.$refs.table.selectRow.ids;
      }
      if (osVersion.size > 1 || osName.size > 1 || osArch.size > 1) {
        this.$message({
          type: "error",
          message: this.$t("configure.issue_configure_error"),
        });
        return false;
      } else {
        this.ids = ids;
        this.osName = Array.from(osName)[0];
        this.osVersion = Array.from(osVersion)[0];
        this.osArch = Array.from(osArch)[0];
        return true;
      }
    },
    async handleHostIssue() {
      const issue = await this.getConfigureNews();
      if (issue) {
          this.display = true;
          this.type = "hostInstall";
          this.title = this.$t("configure.host_issue");
      }
    },
    async handleBatchIssue() {
      const issue = await this.getConfigureNews();
      if (issue) {
          this.display = true;
          this.type = "batchInstall";
          this.title = this.$t("configure.batch_issue");
      }
    },
    async handleDeleteOk() {
      let data = {};
      if (this.$refs.table.select_id === "2") {
        const res = await getConfigureItem({
          ...this.$route.query,
          ...this.search_criteria,
          paged: false,
        });
        let ids = [];
        res.data.data.results.map((item) => {
          if (!this.$refs.table.selectRow.excludeIds.includes(item.id)) {
              ids.push(item.id);
          }
        });
        data["ids"] = ids;
      } else {
        data["ids"] = this.$refs.table.selectRow.ids;
      }
      const res = await deleteConfigureItem(data);
      if (res.data.code == "0") {
        this.$message({
          type: "success",
          message: res.data.message,
        });
      } else {
        this.$message({
          type: "error",
          message: res.data.message,
        });
      }
      this.display = false;
      this.edit_id = null;
      this.type = "";
      this.$refs.table.handleSearch();
    },
    getNormalLibary() {
      getStandardLib().then((res) => {
        let results = res.data.data && res.data.data.results;
        let archs = [];
        let versions = [];
        let names = [];
        results.forEach((item) => {
          if (!names.includes(item.name)) {
            names.push(item.name);
            this.search_data["standardName"].items.push({
              key: item.name,
              name: item.name,
            });
          }
          if (!archs.includes(item.cpuArch)) {
            archs.push(item.cpuArch);
            this.search_data["standardArch"].items.push({
              key: item.cpuArch,
              name: item.cpuArch,
            });
          }
          if (!versions.includes(item.version)) {
            versions.push(item.version);
            this.search_data["standardVersion"].items.push({
              key: item.version,
              name: item.version,
            });
          }
        });
      });
    },
    getConfigureInfo() {
      getClassInfo().then((res) => {
        let data = res.data.data;
        let configTypes = Object.keys(data);
        let files = [];
        let attrs = [];
        configTypes.forEach((key) => {
          this.search_data["configType"].items.push({ key, name: key });
          data[key].forEach((item) => {
            for (let k in item) {
              const attrIndex = attrs.indexOf(k);
              if (attrIndex < 0) {
                attrs.push(k);
                this.search_data["attribute"].items.push({ key: k, name: k });
              }
              const index = files.indexOf(item[k]);
              if (index < 0) {
                files.push(item[k]);
                this.search_data["filePath"].items.push({
                  key: item[k],
                  name: item[k],
                });
              }
            }
          });
        });
      });
    },
  },
  data() {
    return {
      disableName: false,
      type: "",
      edit_id: "",
      d_normal: true,
      title: "",
      osName: "",
      osVersion: "",
      osArch: "",
      display: false,
      delete_content: "",
      search_criteria: {
        sortBy: "id",
        sortOrder: "desc",
      },
      ids: [],
      search_data: {
        name: {
          name: "name",
          type: "text",
        },
        standardName: {
          name: "configure.normal_library_name",
          type: "select",
          items: [],
          func: this.getNormalLibary,
        },
        standardArch: {
          name: "system.architecture",
          type: "select",
          items: [],
        },
        standardVersion: {
          name: "system.version",
          type: "select",
          items: [],
        },
        configType: {
          name: "configure.configure_type",
          type: "select",
          items: [],
          func: this.getConfigureInfo,
        },
        attribute: {
          name: "attribute",
          type: "select",
          items: [],
        },
        baseline: {
          name: "configure.configure_value",
          type: "text",
        },
        flag: {
          name: "configure.restart_sign",
          type: "select",
          items: [
            { key: true, name: this.$t("true") },
            { key: false, name: this.$t("false") },
          ],
        },
        filePath: {
          name: "configure.file_path",
          type: "select",
          items: [],
        },
      },
    };
  },
};
</script>

<style>
</style>